<template>
    <div class="adduser">
        <Layout>
            <Header class="header">
                <Row>
                    <Col :span="20">
                        <div>
                            <span class="border-left"></span>
                            添加成员
                        </div>
                    </Col>
                    <Col :span="4">
                        <div class="back">
                            <span class="back-btn" @click="back">
                                <Icon type="ios-arrow-back" />
                                返回
                            </span>
                        </div>
                    </Col>
                </Row>
            </Header>
            <Content class="content">
                <div class="card-add">
                    <div class="ivu-card ivu-card-bordered ivu-card-dis-hover">
                        <div class="ivu-card-head">
                            <p data-v-57b29fc1="">添加成员</p>
                        </div>
                        <div class="ivu-card-body"> 
                            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="120" style="width:40%">
                                <FormItem label="成员姓名" prop="name">
                                    <Input v-model="formValidate.name" />
                                </FormItem>
                                <FormItem label="登录账号" prop="account">
                                    <Input v-model="formValidate.account" placeholder="建议填写用户手机号或者电子邮箱"/>
                                </FormItem>
                                <FormItem label="角色配置">
                                    <Button type="primary" @click="dialogFormVisible = true">{{body ? '角色已配置' : '打开角色配置'}}</Button><span>&nbsp;(不配置则默认为基础角色)</span>
                                </FormItem>
                                <!-- <FormItem label="服务提成（市级）" prop="rate" class="hidden ivu-form-item-required" :class="isAreaShow(4) ? 'show' : ''">
                                    <Input v-model="formValidate.rate">
                                        <span slot="append">%</span>
                                    </Input>
                                </FormItem>
                                <FormItem label="服务提成（省级）" prop="rate" class="hidden ivu-form-item-required" :class="isAreaShow(3) ? 'show' : ''">
                                    <Input v-model="formValidate.rate">
                                        <span slot="append">%</span>
                                    </Input>
                                </FormItem> -->
                                <FormItem label="登录密码" prop="new_password">
                                    <Input type="password" v-model="formValidate.new_password" />
                                </FormItem>
                                <FormItem label="确认密码" prop="confirmPassword" class="ivu-form-item-required">
                                    <Input type="password" v-model="formValidate.confirmPassword" />
                                </FormItem>
                                <FormItem label="备注信息" prop="remark">
                                    <Input v-model="formValidate.remark" type="textarea" :autosize="{minRows: 5,maxRows: 10}" placeholder="请输入内容"></Input>
                                </FormItem>
                                <FormItem>
                                    <Button type="primary" @click="handleSubmit('formValidate')">提交</Button>
                                    <Button @click="() => {$refs.formValidate.resetFields()}" style="margin-left: 8px">重置</Button>
                                </FormItem>
                            </Form>
                        </div>
                    </div>
                </div>
            </Content>

            <el-dialog title="角色设定" :visible.sync="dialogFormVisible" class="dialog_box">
                <p style="margin-left:10px">提示：不选择默认为基础角色</p>
                <el-checkbox-group size="mini" v-model="selectedRoles" @change="roleChange">
                    <el-checkbox border v-for="(item,index) in roles" :key="index" :label="item.id" >{{item.name}}</el-checkbox>
                </el-checkbox-group>

                <Divider v-show="isAreaShow || isTownShow || isProviceShow || isRateShow" />
                
                <div class="role_edit_box">
                    <div class="ivu-form" style="margin-top:20px;width:100%">
                        <div class="ivu-form-item-required ivu-form-item fead hidden" :class="isAreaShow ? 'show' : ''">
                            <label class="ivu-form-item-label" style="width: 120px;">代理区域(区县)</label>
                            <div class="ivu-form-item-content  u_content" style="margin-left: 120px;">
                                <!-- <ul class="u_list">
                                    <li class="one" v-for="(item,i) in areaList" :key="i">{{item}}</li>
                                </ul> -->
                                <Cascader class="u_input" v-for="(item,i) in formData.area.address" :key="i" :data="area" :load-data="loadAreaData" filterable v-model="formData.area.address[i]"></Cascader>
                                <Input v-model="formData.area.rate" style="width:200px" v-show="formData.area.address.length == 1" placeholder="请填写收益比例">
                                    <span slot="append">%</span>
                                </Input>
                                <div class="addArea addBtn" @click="addArea" v-show="formData.area.address.length < 1">+</div>
                                <div class="tips" v-show="tips && (formData.area.address.length < 1|| formData.area.address[0].length < 1)">{{tips}}</div>
                            </div>
                        </div>
                        <div class="ivu-form-item-required ivu-form-item fead hidden" :class="isTownShow ? 'show' : ''">
                            <label class="ivu-form-item-label" style="width: 120px;">代理区域(市级)</label>
                            <div class="ivu-form-item-content u_content">
                                <!-- <ul class="u_list">
                                    <li class="one" v-for="(item,i) in townList" :key="i">{{item}}</li>
                                </ul> -->
                                <Cascader class="u_input" v-for="(item,i) in formData.town.address" :key="i" :data="town" :load-data="loadTownData" filterable v-model="formData.town.address[i]"></Cascader>
                                <Input v-model="formData.town.rate" style="width:200px" v-show="formData.town.address.length == 1" placeholder="请填写收益比例">
                                    <span slot="append">%</span>
                                </Input>
                                <div class="addTown addBtn" @click="addTown" v-show="formData.town.address.length < 1">+</div>
                                <div class="tips" v-show="tips && (formData.town.address.length < 1|| formData.town.address[0].length < 1)">{{tips}}</div>
                            </div>
                        </div>
                        <div class="ivu-form-item-required ivu-form-item fead hidden" :class="isProviceShow ? 'show' : ''">
                            <label class="ivu-form-item-label" style="width: 120px;">代理区域(省级)</label>
                            <div class="ivu-form-item-content u_content" style="margin-left: 120px;">
                                <!-- <ul class="u_list">
                                    <li class="one" v-for="(item,i) in provinceList" :key="i">{{item}}</li>
                                </ul> -->
                                <Cascader class="u_input" v-for="(item,i) in formData.province.address" :key="i" :data="province" filterable v-model="formData.province.address[i]"></Cascader>
                                <Input v-model="formData.province.rate" style="width:200px" v-show="formData.province.address.length == 1" placeholder="请填写收益比例">
                                    <span slot="append">%</span>
                                </Input>
                                <div class="addTown addBtn" @click="addProvince" v-show="formData.province.address.length < 1">+</div>
                                <div class="tips" v-show="tips && (formData.province.address.length < 1 || formData.province[0].address.length < 1)">{{tips}}</div>
                            </div>
                        </div>
                        <div class="ivu-form-item-required ivu-form-item fead hidden" :class="isRateShow ? 'show' : ''">
                            <label class="ivu-form-item-label" style="width: 120px;">合伙人提成</label>
                            <div class="ivu-form-item-content" style="margin-left: 120px;">
                                <Input v-model="formData.rate" style="width:200px">
                                    <span slot="append">%</span>
                                </Input>
                                <div class="tips" v-show="tips2">请填写合伙人提成</div>
                            </div>
                        </div>
                        
                    </div>
                    
                </div>
                <div slot="footer" class="dialog-footer">
                    <!-- <el-button @click="handleCancel">取 消</el-button> -->
                    <el-button type="primary" @click="saveRoles">确 定</el-button>
                </div>
            </el-dialog>
            
            <Footer>
                <p class="copy-right">Copyright © {{host}}, All Rights Reserved.</p>
            </Footer>
        </Layout>
    </div>
    
</template>

<script>
    import * as api from '@/api/api'
    export default {
        data(){
            //代理区域验证规则
            const territoryCheck = (rule, value, callback) => {
                if (this.roleState) {
                    if(value.length == 0) {
                        callback(new Error('请选择代理区域'));
                    }else {
                        callback();
                    }
                }else {
                    callback();
                }
            };
            //角色验证规则
            const roleCheck = (rule, value, callback) => {
                callback();
            };
            //服务提成验证规则
            const rateCheck = (rule, value, callback) => {
                if (this.roleState) {
                    if(value === '') {
                        callback(new Error('请填写服务提成'));
                    }else {
                        callback();
                    }
                }else {
                    callback();
                }
            };
            //确认密码验证规则
            const validatePassCheck = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次填写密码'));
                } else if (value !== this.formValidate.new_password) {
                    callback(new Error('两次密码不一致'));
                } else {
                    callback();
                }
            };
            return {
                host: window.location.host,
                loading: this.$store.state,
                roles: [],//角色列表
                //表单
                formValidate: {
                    name: '',//成员姓名
                    account: '',//成员账号
                    new_password: '',//密码
                    confirmPassword: '',//确认密码
                    remark: '',//备注
                },
                //验证规则
                ruleValidate: {
                    name: [
                        { required: true, message: '请填写成员姓名', trigger: 'blur' },
                    ],
                    account: [
                        { required: true, message: '请填写登录账号', trigger: 'blur' }
                    ],
                    new_password: [
                        { required: true, message: '请填写登录密码', trigger: 'blur' },
                        { type: 'string', min: 6, message: '密码至少是6位字符', trigger: 'blur' }
                    ],
                    confirmPassword: [
                        { validator: validatePassCheck, trigger: 'change' }
                    ]
                },
                //状态
                roleState: '',//
                //区域选择---省/自治区/直辖市
                province: [],
                town: [],
                area: [],
                addBtn: true,
                dialogFormVisible: false,
                roles: [],
                selectedRoles: [],
                province: [], //省
                town: [], //市
                area: [], //区县
                formData: {
                    area: {
                        rate: '',
                        address: []
                    },
                    town: {
                        rate: '',
                        address: []
                    },
                    province: {
                        rate: '',
                        address: []
                    },
                    rate: ''
                },
                oldData: {
                    area: {
                        rate: '',
                        address: []
                    },
                    town: {
                        rate: '',
                        address: []
                    },
                    province: {
                        rate: '',
                        address: []
                    },
                    rate: ''
                },
                areaList: [],
                townList: [],
                provinceList: [],
                editUserId: null,
                isAreaShow: false,
                isTownShow: false,
                isProviceShow: false,
                isRateShow: false,
                body: '',
                tips: '',
                tips2: false
            }
        },
        mounted(){
            this.getRoles()
        },

        computed: {

        },

        watch: {
            
        },
        
        methods: {
            back() {
                this.$router.back();
            },
            // addRole() {
            //     if(this.formValidate.role_id.length < 4) {
            //         this.formValidate.role_id.push('');
            //     }else {
            //         this.$Notice.error({
            //             title: '错误',
            //             desc: '最多只能添加4个角色',
            //         });
            //     }
            // },

            //获取角色列表
            getRoles() {
                let body = {
                    model: 'Roles',
                    with: {
                        0: 'roleUsers'
                    },
                    contUser: '',
                    offset: 0,
                    limit: 10000,
                    orderBy: '',
                    condition: {
                        is_start: '1',
                        is_delete: '0'
                    }
                };
                api.getDataList(body).then(res => {
                    if (res.data.code === 200) {
                        this.roles = res.data.data.data;
                        this.getProvince();
                    }
                })
            },
            //角色设定
            roleConfig(userId,rate) {
                this.editUserId = userId;
                this.isAreaShow = false;
                this.isTownShow = false;
                this.isProviceShow = false;
                this.isRateShow = false;
                this.selectedRoles = [];
                this.formData = {
                    area: {
                        rate: '',
                        address: []
                    },
                    town: {
                        rate: '',
                        address: []
                    },
                    province: {
                        rate: '',
                        address: []
                    },
                    rate: ''
                };
                this.areaList = [];
                this.provinceList = [];
                this.townList = [];
                let body = {
                    uid: userId
                }
                this.loading.isLoading = true;
                api.getRoleInfo(body).then(res => {
                    this.loading.isLoading = false;
                    if(res.data.code == 200) {
                        for (const item of res.data.data.data) {
                            this.selectedRoles.push(item.role_id);
                            this.roleChange(this.selectedRoles);
                            if(item.role_id == 3) {
                                // let one = [];
                                // one.push(item.territory + ',' + item.city_id)
                                // this.formData.province.push(one);
                                // console.log(this.formData.province)
                                // one.push(item.territory);
                                this.provinceList.push(item.territory);
                                // console.log(this.provinceList)
                            }
                            if(item.role_id == 4) {
                                // let one = [];
                                // one.push(item.territory.split('/')[0]);
                                // one.push(item.territory.split('/')[1] + ',' + item.city_id)
                                // this.formData.town.push(one)
                                // console.log(this.formData.town)
                                this.townList.push(item.territory)
                            }
                            if(item.role_id == 5) {
                                // let one = [];
                                // one.push(item.territory.split('/')[0]);
                                // one.push(item.territory.split('/')[1]);
                                // one.push(item.territory.split('/')[2] + ',' + item.city_id);
                                // this.formData.area.push(one);
                                this.areaList.push(item.territory)
                            }
                            if(item.role_id == 2) {
                                this.formData.rate = item.rate;
                            }
                        }
                    }else {
                        this.$Notice.error({
                            title: '错误',
                            desc: res.data.msg
                        });
                    }

                }).catch(err => {
                    console.error(err)
                })
                this.dialogFormVisible = true;
            },
            roleChange(roles) {
                let reg1 = /3/;
                let reg2 = /4/;
                let reg3 = /5/;
                let reg4 = /2/;
                let str = roles.join(',');
                if (reg1.test(str)) {
                    this.isProviceShow = true;
                } else {
                    this.isProviceShow = false;
                    this.formData.province.address = [];
                    this.formData.province.rate = ''
                }
                if (reg2.test(str)) {
                    this.isTownShow = true;
                } else {
                    this.isTownShow = false;
                    this.formData.town.address = [];
                    this.formData.town.rate = ''
                }
                if (reg3.test(str)) {
                    this.isAreaShow = true;
                } else {
                    this.isAreaShow = false;
                    this.formData.area.address = [];
                    this.formData.area.rate = ''
                }
                if (reg4.test(str)) {
                    this.isRateShow = true;
                } else {
                    this.isRateShow = false;
                    this.formData.rate = '';
                }
            },
            saveRoles() {
                let body = {
                    "role_ids": []
                }
                console.log(this.formData)
                if(this.isAreaShow) {
                    if(this.formData.area.address.length < 1 || this.formData.area.address[0].length < 1) {
                        this.tips  = "请选择代理区域";
                        return false;
                    }
                }
                if(this.isTownShow) {
                    if(this.formData.town.address.length < 1 || this.formData.town.address[0].length < 1) {
                        this.tips  = "请选择代理区域";
                        return false;
                    }
                }
                if(this.isProviceShow) {
                    if(this.formData.province.address.length < 1 || this.formData.province.address[0].length < 1) {
                        this.tips  = "请选择代理区域";
                        return false;
                    }
                }
                if(this.isRateShow && !this.formData.rate) {
                    this.tips2 = true;
                    return false;
                }
                if(this.formData.area.address.length > 0) {
                    for (const item of this.formData.area.address) {
                        if(item && item.length > 0) {
                            let one = {
                                "role_id": 5,
                                "city_id": item[2].split(',')[1],
                                "territory": item[0] + '/' + item[1] + '/' + item[2].split(',')[0],
                                "rate": this.formData.area.rate
                            }
                            body.role_ids.push(one);
                        }
                    }
                }
                if(this.formData.town.address.length > 0) {
                    for (const item of this.formData.town.address) {
                        if(item && item.length > 0) {
                            let one = {
                                "role_id": 4,
                                "city_id": item[1].split(',')[1],
                                "territory": item[0] + '/' + item[1].split(',')[0],
                                "rate": this.formData.town.rate
                            }
                            body.role_ids.push(one);
                        }
                    }
                }
                if(this.formData.province.address.length > 0) {
                    for (const item of this.formData.province.address) {
                        // console.log(item)
                        if(item && item.length > 0) {
                            let one = {
                                "role_id": 3,
                                "city_id": item[0].split(',')[1],
                                "territory": item[0].split(',')[0],
                                "rate": this.formData.province.rate
                            }
                            body.role_ids.push(one);
                        }
                    }
                }
                if(this.formData.rate) {
                    let one = {
                        "role_id": 2,
                        "city_id": 10000,
                        "territory": '中国',
                        "rate": this.formData.rate
                    }
                    body.role_ids.push(one);
                }
                for (const item of this.selectedRoles) {
                    if(item != 2 && item != 3 && item !=4 && item != 5) {
                        let one = {
                            "role_id": item * 1,
                            "city_id": 10000,
                            "territory": '中国',
                            "rate": '0'
                        }
                        body.role_ids.push(one);
                    }
                }
                body.role_ids = JSON.stringify(body.role_ids);
                // console.log(body)
                this.dialogFormVisible = false;
                if(JSON.parse(body.role_ids).length > 0) {
                    this.body = body;
                }
            },
            

            handleSubmit(name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        let role_ids = [
                            {
                                "role_id": 7,
                                "city_id": 10000,
                                "territory": '中国',
                                "rate": '0'
                            }
                        ]
                        let body = {
                            account: this.formValidate.account,
                            name: this.formValidate.name,
                            role_ids: this.body.role_ids || JSON.stringify(role_ids),
                            psd: this.formValidate.new_password,
                            remark: this.formValidate.remark
                        }
                        // console.log(body)
                        // return false
                        this.loading.isLoading = true;
                        api.addUser(body).then(res => {
                            this.loading.isLoading = false;
                            if(res.data.code == 200) {
                                 this.$Notice.success({
                                    title: '提示',
                                    desc: '恭喜你，添加成功！'
                                });
                                this.$router.push({name: 'UserList'})
                            }else {
                                this.$Notice.error({
                                    title: '错误',
                                    desc: res.data.msg,
                                });
                            }
                            // if(res.data)
                        }).catch(err => {
                            this.$Notice.error({
                                title: '错误',
                                desc: err,
                            });
                        })
                    }else {
                        console.log('err')
                    }
                })
            },
            //省市区
            getProvince() {
                let body = {
                    model: 'Provinces',
                    limit: 1000,
                    offset: 0,
                    orderBy: 'id asc'
                };
                //省
                api.getDataList(body).then(res => {
                    this.loading.isLoading = false;
                    let data = res.data.data.data;
                    // if(roleState === '3') {
                    for (const item of data) {
                        let one = {
                            value: item.province_name + ',' + item.id,
                            label: item.province_name,
                            id: item.id,
                            type: 0
                        };
                        this.province.push(one)
                    }
                    // }else {
                    for (const item of data) {
                        let area = {
                            value: item.province_name,
                            label: item.province_name,
                            id: item.id,
                            children: [],
                            loading: false,
                            type: 0
                        };
                        let town = {
                            value: item.province_name,
                            label: item.province_name,
                            id: item.id,
                            children: [],
                            loading: false,
                            type: 0
                        };
                        this.area.push(area);
                        this.town.push(town);
                    }
                    // }
                })
            },
            loadAreaData(item, callback) {
                this.loadData(1, item, callback);
            },

            loadTownData(item, callback) {
                this.loadData(2, item, callback);
            },

            loadData(status, item, callback) {
                item.loading = true;
                if (item.type === 0) {
                    let body = {
                        model: 'Citys',
                        limit: 1000,
                        offset: 0,
                        orderBy: 'id asc',
                        condition: {
                            province_id: item.id
                        }
                    };
                    //市
                    api.getDataList(body).then(res => {
                        let data = res.data.data.data;
                        let city = [];
                        if (status === 2) {
                            for (const citys of data) {
                                let one = {
                                    value: citys.city_name + ',' + citys.id,
                                    label: citys.city_name,
                                    id: citys.id,
                                    type: 1
                                };
                                city.push(one)
                            }
                        } else {
                            for (const citys of data) {
                                let one = {
                                    value: citys.city_name,
                                    label: citys.city_name,
                                    id: citys.id,
                                    children: [],
                                    loading: false,
                                    type: 1
                                };
                                city.push(one)
                            }
                        }
                        item.children = city;
                        item.loading = false;
                        callback();
                    })
                } else if (item.type === 1) {
                    let body = {
                        model: 'Areas',
                        limit: 1000,
                        offset: 0,
                        orderBy: 'id asc',
                        condition: {
                            city_id: item.id
                        }
                    };
                    //区
                    api.getDataList(body).then(res => {
                        let data = res.data.data.data;
                        let area = [];
                        for (const areas of data) {
                            let one = {
                                value: areas.area_name + ',' + areas.id,
                                label: areas.area_name,
                            };
                            area.push(one)
                        }
                        item.children = area;
                        item.loading = false;
                        callback();
                    })
                }

            },
            addArea() {
                this.formData.area.address.push([]);
            },
            addTown() {
                this.formData.town.address.push([]);
            },
            addProvince() {
                this.formData.province.address.push([]);
            }
        }  
    }
</script>


<style lang="less">
    @import '../../../assets/styles/constant.less';
    .adduser{
        width: 100%;
        height: 100%;
        overflow-x: hidden;
        overflow-y: auto;
        background-color: #f5f7f9;
        .ivu-layout{
            min-height: 100%;
        }
        .header{
            font-size: 14px;
            line-height: 40px;
            height: 40px !important;
            color: #434343;
            padding: 0 50px;
            background-color: @background;
            border-bottom: 1px solid #ddd;
            .border-left {
                border-left: 5px solid @baseColor;
                margin-right: 4px;
            }
            .back{
                text-align: right;
                color: #999;
                .back-btn{
                    cursor: pointer;
                    background-color: #fff;
                    padding: 6px 10px;
                    border: 1px solid #ddd;
                }
            }
        }
        .content{
            width: 100%;
            min-height: 76%;
            padding: 20px 60px;
            .card-add{
                margin-top: 20px;
                .ivu-card-head{
                    background-color: #f2f2f2;
                }
                .ivu-card-body{
                    display: flex;
                    justify-content: space-around;
                }
                .hidden{
                    height: 0;
                    overflow: hidden;
                    transition: all 0.3s;
                    margin-bottom: 0;
                }
                .hidden.show{
                    height: 33px;
                    margin-bottom: 24px;
                    overflow:initial;
                }
            }
        }
        .dialog_box {
            .role_edit_box {
                display: flex;
                .ivu-form-item-content {
                    display: flex;
                }
                .u_list {
                    display: flex;
                    // flex-wrap: wrap;
                    .one {
                        border: 1px dashed #aaa;
                        padding: 0 10px;
                        margin-right: 10px;
                        height: 32px;
                    }
                }
            }

            .fead {
                transition: all 0.3s;
            }

            .fead.show {
                height: auto;
                margin-bottom: 24px;
                overflow: initial;
            }

            .hidden {
                height: 0;
                overflow: hidden;
                margin-bottom: 0;
            }
            .u_content {
                margin-left: 120px;
                display: flex;
                flex-wrap: wrap;
            }
            .u_input {
                width:200px;
                display: inline-block;
                margin-right: 4px;
                margin-bottom: 10px;
            }
            .addBtn {
                display: inline-block;
                border: 1px dashed #aaa;
                padding: 0 10px;
                height: 32px;
                cursor: pointer;
            }
            .tips {
                color: red;
                margin-left: 10px;
            }
        }
        .copy-right{
            text-align: center;
            color: #aaa;
            font-size: 12px;
        }
    }
</style>